package com.wang.pubsub;

import com.rabbitmq.client.*;
import com.wang.utils.RabbitMqUtil;

import java.io.IOException;


/**
 * @BelongsProject: RabbitMqLearn
 * @BelongsPackage: com.wang
 * @Author: wang fei
 * @CreateTime: 2023-02-03  15:58
 * @Description: TODO 发布订阅模式-fanout 对于之前的队列模式，是没有办法解决⼀条消息同时被多个消费者消费。于是使⽤发布订阅模式来实现。
 * @Version: 1.0
 */
public class MyConsumer1{
    //发布订阅模式
    //定义交换机名称
    public  static String EXCHANGE_NAME = "my_fanout_exchange";

    //定义队列名称
    public  static String QUEUE_NAME = "my_fanout_queue1";


    public static void main(String[] args) throws Exception {
        Connection connection = RabbitMqUtil.getConnection();
        Channel channel = connection.createChannel();
        //声名队列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        //声名交换机
        channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
        //将队列绑定到交换机上
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "");

        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String s, Envelope envelope, AMQP.BasicProperties basicProperties, byte[] bytes) throws IOException {
                System.out.println("接收到消息为:" + new String(bytes));
            }
        };

        //监听队列
        channel.basicConsume(QUEUE_NAME, true,consumer);


    }
}

